// pages/statistics/statistics.js
const app = getApp();

Page({
  data: {
    timeRange: 'month', // week, month, year, all
    gameType: 'all',
    statistics: {
      totalGames: 0,
      totalTransactions: 0,
      totalScore: 0,
      winCount: 0,
      loseCount: 0,
      avgScore: 0,
      winRate: 0
    },
    chartData: [],
    loading: true
  },

  onLoad: function() {
    // 检查登录状态
    if (!app.globalData.userInfo) {
      wx.navigateTo({ url: '/pages/login/login' });
      return;
    }
    
    this.loadStatistics();
  },

  // 加载统计数据
  loadStatistics: function() {
    const { timeRange, gameType } = this.data;
    const that = this;
    
    this.setData({ loading: true });
    
    wx.request({
      url: app.globalData.apiBaseUrl + '/user/statistics',
      method: 'GET',
      header: {
        'Authorization': 'Bearer ' + app.globalData.token
      },
      data: {
        time_range: timeRange,
        game_type: gameType
      },
      success: (res) => {
        if (res.data.code === 200) {
          that.setData({
            statistics: res.data.data.statistics,
            chartData: res.data.data.chart_data
          });
          that.renderChart();
        }
      },
      complete: () => {
        that.setData({ loading: false });
      }
    });
  },

  // 切换时间范围
  switchTimeRange: function(e) {
    const timeRange = e.currentTarget.dataset.range;
    this.setData({ timeRange });
    this.loadStatistics();
  },

  // 切换游戏类型
  switchGameType: function(e) {
    const gameType = e.currentTarget.dataset.type;
    this.setData({ gameType });
    this.loadStatistics();
  },

  // 渲染图表
  renderChart: function() {
    // 这里可以使用小程序的canvas或者第三方图表库来渲染统计图表
    // 由于实际开发中可能需要引入图表库，这里只做简单的模拟
    console.log('渲染图表数据:', this.data.chartData);
  },

  // 查看详细记录
  viewDetails: function() {
    wx.navigateTo({ url: '/pages/transactions/transactions' });
  },

  // 分享统计数据
  shareStatistics: function() {
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage']
    });
  }
});